
import React, {useEffect, useRef, useState} from 'react';
import {
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
    Modal,
    Image,
    Platform,
    Dimensions,
    ScrollView,
    Linking, Alert, ActivityIndicator
} from 'react-native';
import LinearGradient from "react-native-linear-gradient";
import HttpUtils from "../../../utils/HttpUtils";
import HttpUrls from "../../../utils/HttpUrls";
import {ToastToUser} from "../../../utils/CustomToast";
import CommonDialog from "../../../components/dialog/CommonDialog";

const { height } = Dimensions.get('window');

const CheckBox = ({ label, value, onValueChange, price }) => (
    <TouchableOpacity onPress={onValueChange} style={styles.optionRow}>
        <Text style={styles.optionLabel}>{label}</Text>
        <View style={styles.priceAndCheckbox}>
            <Text style={styles.price}>{price}</Text>
            <TouchableOpacity onPress={onValueChange} style={styles.checkbox}>
                {value && <View style={styles.checkboxSelected} />}
            </TouchableOpacity>
        </View>
    </TouchableOpacity>
);

const RadioButton = ({ label, value, onSelect }) => (
    <TouchableOpacity onPress={onSelect} style={styles.radioButtonContainer}>
        <View style={[styles.radioButton, value && styles.radioButtonSelected]}>
            {value && <View style={styles.radioButtonInner} />}
        </View>
        <Text style={styles.radioLabel}>{label}</Text>
    </TouchableOpacity>
);

const LoadingModal = ({ visible, text = "加载中..." }) => {
    return (
        <Modal
            transparent={true}
            animationType="none"
            visible={visible}
            onRequestClose={() => {}}
        >
            <View style={styles.modalBackground}>
                <View style={styles.activityIndicatorWrapper}>
                    <ActivityIndicator
                        animating={true}
                        size="large"
                        color="#666666"
                    />
                    <Text style={styles.loadingText}>{text}</Text>
                </View>
            </View>
        </Modal>
    );
};

const logisticsService = (setLoading) => {
    // 显示加载提示
    if (setLoading) {
        console.log('显示加载提示');
        setLoading(true);
    }
    HttpUtils.getRequest(HttpUrls.getCustomerServicePhone, {})
        .then((result) => {
            if (result.code == 0) {
                const url = `tel:${result.data}`;
                Linking.canOpenURL(url).then(supported => {
                    if (!supported) {
                        return Alert.alert('提示', `您的设备不支持该功能，请手动拨打 ${result.data}`, [
                            {text: '确定'}
                        ]);
                    }
                    return Linking.openURL(url);
                }).catch(err => Alert(err));
            } else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        })
        .catch((error) => {
            ToastToUser(error)
        })
        .finally(() => {
            // 隐藏加载提示
            if (setLoading) {
                setLoading(false);
            }
        })
}

const formPrice = (price) => {
    if(!price){
        return 0
    }
    return parseFloat(price/100).toFixed(2)
}

const LogisticDialog = ({ visible, confrimText, cancelText, onConfrim, onCancel, data }) => {
    const isIos = Platform.OS == 'ios';

    const [selectedPlan, setSelectedPlan] = useState('40');
    const [pickupMethod, setPickupMethod] = useState('cart');
    const [deliveryMethod, setDeliveryMethod] = useState('cart');
    // 添加 loading 状态
    const [loading, setLoading] = useState(false);

    const [dialogVisible, setDialogVisible] = useState(false);

    const [fdPrice, setFdPriceMethod] = useState('');
    // 当 data 更新时，重新计算并设置默认价格
    useEffect(() => {
        if (data && data.segmentSmallBoardAndSmallBoardFee) {
            const price = formPrice(data.segmentSmallBoardAndSmallBoardFee);
            setFdPriceMethod(price + '');
        }
    }, [data]); // 依赖于 data 变化

    const handlePlanChange = (plan) => {
        setSelectedPlan(plan);
    }
    const handlePickupMethodChange = (method, type) => {
        let currentPickupMethod = pickupMethod;
        let currentDeliveryMethod = deliveryMethod;
        if(type == 'pickup'){
            setPickupMethod(method);
            currentPickupMethod = method;
        }
        if(type == 'delivery'){
            setDeliveryMethod(method);
            currentDeliveryMethod = method;
        }
        console.log('method', method, type)
        if(selectedPlan == 10){
            if(currentPickupMethod == 'cart' && currentDeliveryMethod == 'cart'){ //小板+小板
                console.log('小板+小板')
                setFdPriceMethod(formPrice(data?.segmentSmallBoardAndSmallBoardFee))
            }
            if(currentPickupMethod == 'driver' && currentDeliveryMethod == 'driver'){ //代驾+代驾
                console.log('代驾+代驾')
                setFdPriceMethod(formPrice(data?.segmentDrivingServiceAndDrivingServiceFee))
            }
            if(currentPickupMethod == 'cart' && currentDeliveryMethod == 'driver'){ //小板+代驾
                console.log('小板+代驾')
                setFdPriceMethod(formPrice(data?.segmentSmallBoardAndDrivingServiceFee))
            }
            if(currentPickupMethod == 'driver' && currentDeliveryMethod == 'cart'){ //代驾+小板
                console.log('代驾+小板')
                setFdPriceMethod(formPrice(data?.segmentDrivingServiceAndSmallBoardFee))
            }
        }
    }

    const getPriceByPlan = (plan) => {
        switch(plan) {
            case '10': // 分段运输
                return fdPrice;
            case '40': // 全程代驾
                return formPrice(data?.fullServiceDrivingFee);
            case '30': // 全程小板
                return formPrice(data?.fullSmallBoardFee);
            case '0': // 自提
                return formPrice(0);
            default:
                return '';
        }
    };

    return (
        <Modal
            visible={visible}
            transparent={true}
            animationType="slide"
            onRequestClose={onCancel}
        >
            <View style={styles.container}>
                <View style={styles.dialog}>
                    <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: '100%', position: 'relative' }}>
                        <Text style={styles.title}>{'选择运输方案'}</Text>
                        <TouchableOpacity activeOpacity={0.8} onPress={onCancel} style={{ position: 'absolute', right: 10 }}>
                            <Image style={styles.closeIcon} source={require('source/image/comm/icon_close.png')}/>
                        </TouchableOpacity>
                    </View>

                    <ScrollView showsVerticalScrollIndicator={false}>
                        <View style={styles.card}>
                            <View style={styles.cityRow}>
                                <View style={styles.cityIconContainer}>
                                    <View style={[styles.iconCircle, {backgroundColor: '#4285f4'}]}>
                                        <Text style={{color: '#e8f0fe', fontWeight: 'bold'}}>发</Text>
                                    </View>
                                    <View style={styles.dottedLine} />
                                    <View style={[styles.iconCircle, {backgroundColor: '#04942d'}]}>
                                        <Text style={{color: '#e8f0fe', fontWeight: 'bold'}}>收</Text>
                                    </View>
                                </View>
                                <View style={styles.cityTextContainer}>
                                    <View style={styles.cityTextRow}>
                                        <Text style={styles.cityLabel}>起点城市:</Text>
                                        <Text style={styles.cityName}>{data?.originCityStr || ''}</Text>
                                    </View>
                                    <View style={styles.separator} />
                                    <View style={styles.cityTextRow}>
                                        <Text style={styles.cityLabel}>终点城市:</Text>
                                        <Text style={styles.cityName}>{data?.destinationCityStr || ''}</Text>
                                    </View>
                                </View>
                            </View>
                        </View>

                        <View style={styles.card}>
                            <TouchableOpacity activeOpacity={0.8} style={{flexDirection: 'row', alignItems: 'center'}} onPress={() => {
                                setDialogVisible(true)
                            }}>
                                <Text style={styles.cardTitle}>运输方案</Text>
                                <Image style={styles.customerServiceTipIcon} source={require('source/image/question_icon.png')}/>
                            </TouchableOpacity>
                            {/*//transportScheme: 10,//10:分段运输， 20:全程大板， 30:全程小板， 40:全程地跑*/}
                            <CheckBox
                                label="分段运输"
                                price={fdPrice + '元' || ''}
                                value={selectedPlan === '10'}
                                onValueChange={() => handlePlanChange('10')} />

                            {selectedPlan === '10' && (
                                <View style={styles.segmentedOptions}>
                                    <View style={styles.subOptionRow}>
                                        <Text style={styles.subOptionLabel}>提车</Text>
                                        <RadioButton label="小板" value={pickupMethod === 'cart'} onSelect={() => handlePickupMethodChange('cart', 'pickup')} />
                                        <RadioButton label="代驾" value={pickupMethod === 'driver'} onSelect={() => handlePickupMethodChange('driver', 'pickup')} />
                                    </View>
                                    <View style={styles.subOptionRow}>
                                        <Text style={styles.subOptionLabel}>送车</Text>
                                        <RadioButton label="小板" value={deliveryMethod === 'cart'} onSelect={() => handlePickupMethodChange('cart', 'delivery')} />
                                        <RadioButton label="代驾" value={deliveryMethod === 'driver'} onSelect={() => handlePickupMethodChange('driver', 'delivery')} />
                                    </View>
                                </View>
                            )}

                            <CheckBox
                                label="全程代驾"
                                price={formPrice(data?.fullServiceDrivingFee) + '元' || ''}
                                value={selectedPlan === '40'}
                                onValueChange={() => handlePlanChange('40')}
                            />
                            <View style={styles.optionSeparator} />

                            <CheckBox
                                label="全程小板"
                                price={formPrice(data?.fullSmallBoardFee) + '元' || ''}
                                value={selectedPlan === '30'}
                                onValueChange={() => handlePlanChange('30')}
                            />
                            <View style={styles.optionSeparator} />
                            {/*<View style={styles.optionSeparator} />*/}
                            <CheckBox
                                label="自提"
                                price={'0元'}
                                value={selectedPlan === '0'}
                                onValueChange={() => handlePlanChange('0')}
                            />

                        </View>

                        <Text style={styles.hintText}>
                            提示: 若对运费有疑问, 可详询物流客服
                        </Text>

                    </ScrollView>


                    <View style={styles.footer}>
                        <TouchableOpacity activeOpacity={0.8} style={styles.customerService} onPress={() => {
                            logisticsService(setLoading)
                        }}>
                            {/*<Icon name="headset" type="material" color="#555" />*/}
                            <Image style={styles.customerServiceIcon} source={require('source/image/service_icon.png')}/>
                            <Text style={styles.customerServiceText}>物流客服</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.confirmButton}  onPress={()=>{
                            const selectedData = {
                                plan: selectedPlan, // 选中的方案 (10:分段运输, 40:全程代驾, 30:全程小板)
                                price: getPriceByPlan(selectedPlan), // 对应的价格
                                pickupMethod: pickupMethod, // 提车方式 (cart:小板, driver:代驾)
                                deliveryMethod: deliveryMethod, // 送车方式 (cart:小板, driver:代驾)
                            };
                            onConfrim(selectedData);
                        }}>
                            <Text style={styles.confirmButtonText}>{confrimText}</Text>
                        </TouchableOpacity>
                    </View>

                    {/*<View style={styles.bottomBox}>*/}
                    {/*    <TouchableOpacity*/}
                    {/*        activeOpacity={0.8}*/}
                    {/*        style={styles.bottomRightItemBox}*/}
                    {/*        onPress={onCancel}*/}
                    {/*    >*/}
                    {/*        <LinearGradient*/}
                    {/*            start={{ x: 0, y: 0 }}*/}
                    {/*            end={{ x: 1, y: 0 }}*/}
                    {/*            colors={['#F5F5F5', '#F5F5F5']}*/}
                    {/*            style={styles.itemInnerBox}*/}
                    {/*        >*/}
                    {/*            <Text style={styles.bottomRightItemText}>{cancelText}</Text>*/}
                    {/*        </LinearGradient>*/}
                    {/*    </TouchableOpacity>*/}

                    {/*    <TouchableOpacity*/}
                    {/*        activeOpacity={0.8}*/}
                    {/*        style={styles.bottomRightItemBox}*/}
                    {/*        onPress={onConfrim}*/}
                    {/*    >*/}
                    {/*        <LinearGradient*/}
                    {/*            start={{ x: 0, y: 0 }}*/}
                    {/*            end={{ x: 1, y: 0 }}*/}
                    {/*            colors={['#FFEF3A', '#FFDB1B']}*/}
                    {/*            style={styles.itemInnerBox}*/}
                    {/*        >*/}
                    {/*            <Text style={styles.bottomRightItemText}>{confrimText}</Text>*/}
                    {/*        </LinearGradient>*/}
                    {/*    </TouchableOpacity>*/}
                    {/*</View>*/}
                </View>

                {/* 添加 LoadingModal 组件 */}
                <LoadingModal visible={loading} text="请稍后..." />


                <CommonDialog
                    visible={dialogVisible}

                    title={'物流方案'}
                    content={'分段运输：\n' +
                        '是指小板车或者代驾司机上门取车，送到当地物流园，在物流园上大板车;大板车开到目城市的 地物流园卸车，再由小板或者代驾司机送到最终目的地。中长途推荐，不支持豪车运输。\n' +
                        '\n' +
                        '全程代驾：\n' +
                        '是指代驾司机上门拿车，直接开到目的地交车，短途运输推荐选择。\n' +
                        '\n' +
                        '全程小板：\n' +
                        '是小板车上门拿车，也是直接送到目的地交车。运输豪车推荐选择。'}
                    confrimText={'确定'}
                    cancelText={'关闭'}
                    onConfrim={() => {
                       setDialogVisible(false)
                    }}
                    onCancel={() => {
                        setDialogVisible(false)
                    }}
                />

            </View>
        </Modal>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.5)',
        justifyContent: 'flex-end', // 改为从底部弹出
    },
    dialog: {
        width: '100%',
        height: '80%',
        backgroundColor: 'white',
        borderTopLeftRadius: 8,  // 顶部圆角
        borderTopRightRadius: 8, // 顶部圆角
        padding: 16,
        maxHeight: height * 0.8,  // 限制最大高度
    },
    title: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#000000',
    },

    // 底部按钮样式
    bottomBox: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        marginTop: 'auto', // 将按钮推到底部
        marginBottom: 10,
    },
    bottomRightItemBox: {
        width: 110,
        height: 28,
        marginTop: 10,
    },
    itemInnerBox: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 18,
    },
    bottomRightItemText: {
        color: '#222',
        fontSize: 14,
    },

    // 物流方案
    card: {
        backgroundColor: 'white',
        borderRadius: 8,
        padding: 10,
        marginHorizontal: 10,
        marginTop: 5,
    },
    cityRow: {
        flexDirection: 'row',
    },
    cityIconContainer: {
        alignItems: 'center',
        marginRight: 15,
    },
    iconCircle: {
        width: 30,
        height: 30,
        borderRadius: 15,
        justifyContent: 'center',
        alignItems: 'center',
    },
    dottedLine: {
        height: 30,
        width: 1,
        borderLeftWidth: 1,
        borderLeftColor: '#ccc',
        borderStyle: 'dashed',
    },
    cityTextContainer: {
        flex: 1,
    },
    cityTextRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 14,
    },
    cityLabel: {
        fontSize: 16,
        color: '#555',
        width: 80,
    },
    cityName: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    separator: {
        height: 1,
        backgroundColor: '#f0f0f0',
    },
    cardTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        marginRight: 5,
    },
    customerServiceTipIcon: {
        width: 18,
        height: 18,
    },
    optionRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 15,
    },
    optionLabel: {
        fontSize: 16,
    },
    priceAndCheckbox: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    price: {
        fontSize: 16,
        color: '#333',
        marginRight: 15,
    },
    checkbox: {
        width: 20,
        height: 20,
        borderWidth: 1,
        borderColor: '#FFDB1B',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 3,
    },
    checkboxSelected: {
        width: 12,
        height: 12,
        backgroundColor: '#FFDB1B',
        borderRadius: 2,
    },
    optionSeparator: {
        height: 1,
        backgroundColor: '#f0f0f0',
    },
    segmentedOptions: {
        paddingLeft: 10,
        paddingTop: 10,
        backgroundColor: '#fafafa',
        marginTop: 10,
    },
    subOptionRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
    },
    subOptionLabel: {
        fontSize: 16,
        color: '#555',
        width: 60,
    },
    radioButtonContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: 20,
    },
    radioButton: {
        height: 20,
        width: 20,
        borderRadius: 10,
        borderWidth: 1,
        borderColor: '#FFDB1B',
        alignItems: 'center',
        justifyContent: 'center',
    },
    radioButtonSelected: {
        borderColor: '#FFDB1B',
    },
    radioButtonInner: {
        height: 10,
        width: 10,
        borderRadius: 5,
        backgroundColor: '#FFDB1B',
    },
    radioLabel: {
        marginLeft: 8,
        fontSize: 16,
    },
    hintText: {
        fontSize: 12,
        color: '#999',
        textAlign: 'center',
        padding: 15,
    },
    footer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 15,
        borderTopWidth: 1,
        borderTopColor: '#f0f0f0',
        backgroundColor: 'white',
    },
    customerService: {
        flexDirection: 'column',
        alignItems: 'center',
    },
    customerServiceIcon: {
        width: 25,
        height: 25,
    },
    customerServiceText: {
        marginLeft: 5,
        fontSize: 14,
        color: '#555',
    },
    confirmButton: {
        backgroundColor: '#FFDB1B',
        paddingVertical: 10,
        paddingHorizontal: 40,
        borderRadius: 5,
    },
    confirmButtonText: {
        color: 'white',
        fontSize: 16,
        fontWeight: 'bold',
    },


    // loading样式
    modalBackground: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'rgba(0,0,0,0.3)',
    },
    activityIndicatorWrapper: {
        backgroundColor: '#FFFFFF',
        height: 100,
        width: 100,
        borderRadius: 10,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    loadingText: {
        marginTop: 10,
        fontSize: 14,
    },

    closeIcon: {
        width: 16,
        height: 16
    },

});

export default LogisticDialog;